import { createProject, saveFile, getProjectInfo } from '../../../../api/index'
const uploadOss = require('../../../../utils/upload/uploadImg.js')
import { uuid, formatTimeTwo } from '../../../../utils/util'

Page({
  data: {
    form: {
      projectName: '',
      type: '',
      projectType: [],
      projectDate: '',
      area: '',
      budget: '',
      province: '',
      city: '',
      region: '',
      detailAddress: '',
      intro: '',
      coverFiles: []
    },
    projectId: '',
    coverFiles: [],
    projectTypeStr: '',
    typeStr: '',
    address: '',
    showAddressModal: false,
    showCatePopup: false,
    typeRange: [
      { label: '个人项目', value: 1 },
      { label: '团队项目', value: 2 }
    ]
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail: { value } }) {
    this.setData({ ['form.' + key]: value })
  },
  changeType ({ detail: { value } }) {
    this.setData({ 'form.type': this.data.typeRange[value].value, typeStr: this.data.typeRange[value].label })
  },
  showCateModal () {
    this.setData({ showCatePopup: true })
  },
  changeCate ({ detail }) {
    let projectType = []
    let projectTypeStr = []
    detail.forEach(item => {
      projectType.push(item.styleId)
      projectTypeStr.push(item.styleName)
    })

    this.setData({ 'form.projectType': projectType, projectTypeStr: projectTypeStr.join(','), showCatePopup: false })
  },
  closeCatePopup () {
    this.setData({ showCatePopup: false })
  },
  selectAddress () {
    this.setData({ showAddressModal: true })
  },
  closeAddressPop () {
    this.setData({ showAddressModal: false })
  },
  async changeAddress ({ detail }) {
    try {
      this.setData({
        'form.province': detail[0].value,
        'form.city': detail[1].value,
        'form.region': detail[2].value,
        showAddressModal: false,
        address: `${detail[0].label}${detail[1].label}${detail[2].label}`
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async changeDate ({ detail: { value } }) {
    try {
      this.setData({ 'form.projectDate': value })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  deleteTempFile ({ currentTarget: { dataset: { index, key } } }) {
    this.data[key].splice(index, 1)
    this.setData({ [key]: this.data[key] })
  },
  deleteFile ({ currentTarget: { dataset: { key } } }) {
    this.setData({ ['form.' + key]: [], 'form.coverUrl': '', 'form.coverId': '' })
  },
  async submit () {
    try {
      if (!this.data.form.projectName) {
        wx.showToast({ title: '请输入项目名称！', icon: 'none' })
        return
      }
      if (!this.data.form.type) {
        wx.showToast({ title: '请选择项目分类！', icon: 'none' })
        return
      }
      if (!this.data.form.projectType.length) {
        wx.showToast({ title: '请选择项目业态！', icon: 'none' })
        return
      }
      if (!this.data.form.province || !this.data.form.city || !this.data.form.region) {
        wx.showToast({ title: '请选择项目地址！', icon: 'none' })
        return
      }
      if (!this.data.form.coverUrl) {
        wx.showToast({ title: '请选择项目封面！', icon: 'none' })
        return
      }
      if (this.locking) return
      this.locking = true
      let query = { ...this.data.form }
      if (query.coverFiles.length) query.coverUrl = query.coverFiles[0].fileReader
      query.projectType = JSON.stringify(query.projectType)
      await createProject({ ...query })
      wx.showToast({ title: '创建成功！', icon: 'none' })
      wx.$nav.redirectTo('/pages/account/project/index/index')
      this.locking = false
    } catch (err) {
      console.log(err)
      this.locking = false
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getDetail () {
    try {
      const { ResultSet } = await getProjectInfo({ projectId: this.data.projectId })
      ResultSet.userData.projectInfo.projectDate = formatTimeTwo(ResultSet.userData.projectInfo.projectDate, 'Y-M-D')
      ResultSet.userData.projectInfo.projectType = JSON.parse(ResultSet.userData.projectInfo.projectType)
      this.data.typeStr = this.data.typeRange.find(item => item.value === ResultSet.userData.projectInfo.type).label
      this.data.address = `${ResultSet.userData.projectInfo.provinceName}${ResultSet.userData.projectInfo.cityName}${ResultSet.userData.projectInfo.regionName}`
      let styles = ResultSet.userData.projectInfo.stylesList.map(item => item.styleName)
      this.data.projectTypeStr = styles.join(',')
      this.data.form = { ...this.data.form, ...ResultSet.userData.projectInfo }
      this.setData({
        form: this.data.form,
        typeStr: this.data.typeStr,
        address: this.data.address,
        projectTypeStr: this.data.projectTypeStr
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  addFile ({ target: { dataset: { key, num } } }) {
    let _this = this
    if (parseInt(num) - this.data.form[key].length === 0) {
      wx.showToast({ title: `最多只能上传${num}图片！`, icon: 'none' })
      return
    }
    wx.chooseMedia({
      count: parseInt(num),
      mediaType: ['image'],
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (file) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileName: file.fileName,
                  fileUrl: file.fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileName: file.fileName,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl,
                fileReader: ResultSet.userData.fileIdList[0].url
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form[key].push(...tempFileList)
        _this.data.form[key].forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key],
          'form.coverUrl': _this.data.form[key][0].fileUrl,
          'form.coverId': _this.data.form[key][0].fileId
        })
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  onLoad ({ id }) {
    if (id) {
      this.setData({ projectId: id })
      this.getDetail()
    }
  }
})